package com.beike.service.serviceImpl;

import com.beike.entity.LessonDesign;
import com.beike.service.AIService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AIServiceImpl implements AIService {

    private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions";
    private static final String API_KEY = "sk-f29b1648ac6742cc960b1883a4716f9c";
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public LessonDesign generateLessonDesign(String name, String subject, String grade, int duration) {
        try {
            // 1. 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("temperature", 0.7);

            // 2. 构建提示词
            String prompt = String.format("为学科为%s，年级为%s，课程名称为%s生成时长为%d分钟的教学设计教案。请注意：不要使用任何特殊符号（如*、#等），仅使用纯文本格式。", subject, grade, name, duration);
            Map<String, String> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", prompt);
            requestBody.put("messages", new Map[]{message});

            // 3. 发送请求
            String requestBodyJson = objectMapper.writeValueAsString(requestBody);

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(DEEPSEEK_API_URL))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + API_KEY)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyJson))
                    .build();

            HttpResponse<String> response = HttpClient.newHttpClient()
                    .send(request, HttpResponse.BodyHandlers.ofString());

            System.out.println("Response Body: " + response.body()); // 打印 API 响应内容

            // 4. 解析响应
            if (response.statusCode() == 200) {
                Map<String, Object> responseMap = objectMapper.readValue(response.body(), new TypeReference<Map<String, Object>>() {
                });
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
                Map<String, Object> firstChoice = choices.get(0);
                Map<String, Object> message1 = (Map<String, Object>) firstChoice.get("message"); // 定义 message 变量
                String content = (String) message1.get("content");

                // 5. 创建并返回 LessonDesign 对象
                LessonDesign design = new LessonDesign();
                design.setName(name);
                design.setSubject(subject);
                design.setGrade(grade);
                design.setDuration(duration);
                design.setKnowledgeGoals(content); // 使用 knowledgeGoals 字段存储生成内容
                return design;
            } else {
                throw new RuntimeException("DeepSeek API 调用失败，状态码：" + response.statusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("生成教学设计时发生错误", e);
        }
    }
}